import React from 'react';
import { comsType, CHECKED, ACCEPT_TYPE, detailTypes } from '../../constants/form';
import { Tools, Icon } from 'weaver-mobile';
import { getSize, getWidthPct, getWidthPX } from './Helper';
import { Map } from 'react-amap';
import loadjs from "loadjs";
import classNames from 'classnames';
import querystring from 'querystring';
import widget from '../../apis/widget';
import board from '../../apis/board';
import getUrlParams from '../../utils/getUrlParams';
import If, {Then, Else} from '../../common/if';

const types = {
  RADIO: 'radio',
  CHECKBOX: 'checkbox'
}
// design与view模式下共用View.js
const modeTypes = {
  DESIGN: 'design',
  VIEW: 'view'
}
const { CHECKBOX, RADIO } = detailTypes; 
const RADIX = 1024;
const getLabel = Tools.getLabel;
const {
  TEXT, DATE, TIME, TEXTAREA, SELECT, COMBOBOX, NUMBER,
  DESCRIPTION, RATING, SIGNATURE, PICTURE, ATTACHMENT,
  NAME, MOBILE, EMAIL, TELEPHONE, ADDRESS, COLUMNPANEL2,
  COLUMNPANEL3, DATATABLE, MAP, TABLELAYOUT, BOARD_ELEMENT
} = comsType;
const Text = ({ data, value }) => (
  <div>
    <input type='text' />
  </div>
);
const DateView = ({ data, value }) => (
  <div>
    <input type='date' defaultValue={value} />
  </div>
);
const TimeView = ({ data, value }) => (
  <div>
    <input type='time' defaultValue={value} />
  </div>
);
const TextareaView = ({ data, value }) => (
  <div className='wea-view-textarea'>
    <textarea
      defaultValue={value}
      rows={3}
    />
    {data.max && data.max.checked === CHECKED ?
      <span className='wea-textarea-tips'>{value.length}/{data.max.value}</span> : ''
    }
  </div>
);

const SelectView = ({ data, value }) => {
  const { options, type, isVertical = '0' } = data;
  const detailtype = type === types.CHECKBOX ? CHECKBOX : RADIO;
  const verticalCls = classNames({
    'wea-edc-select-vertical': !Boolean(isVertical)
  });
  
  return (
    <div className={verticalCls}>
      <div>
        {
          detailtype === RADIO ?
            <React.Fragment>
              {
                options.map((option, index) => (
                  <label key={`${option.showname}_${index}`} className="ant-radio-wrapper">
                    <span className="ant-radio ant-radio">
                      <input type="radio" className="ant-radio-input" />
                      <span className="ant-radio-inner"></span>
                    </span>
                    <span>{option.showname || getLabel('502263', '选项')}</span>
                  </label>
                ))
              }
            </React.Fragment>
            :
            <React.Fragment>
              {
                options.map((option, index) => (
                  <label key={`${option.showname}_${index}`} className="ant-checkbox-group-item ant-checkbox-wrapper">
                    <span className="ant-checkbox">
                      <span className="ant-checkbox-inner"></span>
                      <input type="checkbox" className="ant-checkbox-input" />
                    </span>
                    <span>
                      <span title="选项">{option.showname || getLabel('502263', '选项')}</span>
                    </span>
                  </label>
                ))
              }
            </React.Fragment>
        }
      </div>
    </div>
  );
}

const ComBoboxView = ({ data, value }) => {
  return (
    <div className='wea-edc-select-container'>
      <select>
        <option value=''>{getLabel('502500', '请选择')}</option>
        {data.options.map(opt => (
          <option key={opt.key} value={opt.key}>{opt.showname}</option>
        ))}
      </select>
    </div>
  );
}

const NumberView = ({ data, value }) => (
  <div className='wea-edc-input-conatiner wea-input-normal'>
    <i className='icon-edc-f-number wea-edc-input-icon' />
    <input
      type='number'
      value={value}
    />
  </div>
);

const DescriptionView = ({ data, value }) => (
  <div className='wea-edc-desc-conatiner' dangerouslySetInnerHTML={{ __html: data.desc }} ></div>
)

const RatingView = ({ data, value }) => {
  const { score = 5, icon } = data;
  const hoveredIndex = 0;

  return (
    <div className='rating-img-container'
    >
      {Array(score).fill(1).map((n, i) => {
        const isHighlight = hoveredIndex ? hoveredIndex > i : value > i;

        return (
          <i key={`rating_${i}`} className={`rating-icon rating-icon-${icon} ${isHighlight ? 'highlight' : ''}`}
            data-value={i + 1}
          />
        );
      })}
    </div>
  );
}

const SignatureView = ({ data, value }) => (
  <span>
    <button
      icon='edit'
      type='ghost'
      className='wea-edc-form-btn'
    >
      <i className='anticon anticon-edit'></i>
      {getLabel('502530', '点击开始签署电子签名')}
    </button>
  </span>
);

const PictureView = ({ data, value }) => (
  <div className='mobile-edc-upload-container'>
    <div>
      <div className='edc-upload-img-content'>
        <div className='img-placeholder'>
          <i className='icon-edc-app-plus-circle-fill'></i>
        </div>
        <div>{getLabel('502261', '选择图片')}</div>
        <p>{
          !data.restrictions.maxNum ? '' :
            `(${getLabel('503776', '数量最多$s个').replace(/\$s/, data.restrictions.maxNum)})`
        }</p>
      </div>
    </div>
  </div>
);

const AttachmentView = ({ data, value }) => {
  const { fileType, customType, restrictions } = data;
  const { maxNum, maxSize } = restrictions;
  const acceptTip = (!fileType || fileType === "UNLIMITED") ? "" : (fileType === "CUSTOM" ? customType : ACCEPT_TYPE[fileType]);

  return (<div className='mobile-edc-upload-container'>
    <div>
      <div className='edc-drag-inner'>
        <div>
          <i className='anticon anticon-plus'></i>
        </div>
        <div>
          {
            getLabel('502473', '点击选择上传文件')
          }
          {
            `(${getLabel('505284', '最多$s个').replace('$s', maxNum)})${Number(maxSize.value) * RADIX * RADIX ? getLabel('505285', '限制每个$s以内').replace('$s', getSize(Number(maxSize.value) * RADIX * RADIX)) : ''}`}。{acceptTip && getLabel('506499', '仅支持') + acceptTip.replace(/,/g, '、')
          }
        </div>
      </div>
    </div>
  </div>
  );
}

const NameView = ({ data, value }) => (
  <div className='wea-edc-input-conatiner wea-input-normal'>
    <i className='icon-edc-f-name wea-edc-input-icon' />
    <input type='text' />
  </div>
);

const MobileView = ({ data, value }) => (
  <div className='wea-edc-input-conatiner wea-input-normal'>
    <i className='icon-edc-f-mobile wea-edc-input-icon' />
    <input type='text' length={11} />
  </div>
);

const EmailView = ({ data, value }) => (
  <div className='wea-edc-input-conatiner wea-input-normal'>
    <i className='icon-edc-f-email wea-edc-input-icon' />
    <input type='text'/>
  </div>
);

const TelePhoneView = ({ data, value }) => (
  <div className='wea-edc-input-conatiner wea-input-normal'>
    <i className='icon-edc-f-telephone wea-edc-input-icon' />
    <input type='text'/>
  </div>
);

const AddressView = ({ data, value }) => (
  <div>
    <div className='wea-edc-table-layout'>
      <div className='wea-edc-select-container' style={{'marginTop': 0}}>
        <select>
          <option value=''>{`- ${getLabel('502455', '省/自治区/直辖市')} -`}</option>
        </select>
      </div>
      <div className='wea-edc-select-container' style={{ 'paddingLeft': 5 }}>
        <select>
          <option>{`- ${getLabel('502456', '市区')} -`}</option>
        </select>
      </div>
    </div>
    <div className='wea-edc-table-layout'>
      <div className='wea-edc-select-container' >
        <select>
          <option>{`- ${getLabel('502457', '区/县')} -`}</option>
        </select>
      </div>
    </div>
    <div className='wea-edc-table-layout'>
      <div className=''>
        <input
        type='text'
          className='wea-edc-form-field'
        />
      </div>
    </div>
  </div>
)

const ColumnPanel2View = ({ data, value, renderItem }) => {
  const { size, coms } = data;
  const style = { width: `${1 / size * 100}%` };

  return (
    <div className='wea-edc-columnpanel-row'>
      {Array(size).fill(0).map((s, index) => (
        <div key={`columnpanel_${index}`} style={style}>
          {renderItem(coms[index])}
        </div>
      ))}
    </div>
  );
}

const DataTableView = ({ data, value, renderItem }) => {
  const { coms } = data;

  return (
    <div className='data-table-content'>
      <table className='mobile-edc-data-table'>
        <thead className='edc-thead'>
          <tr style={{'height': 46}}>
            <th className='mobile-edc-app-tablecheckbox'>
              <label className="ant-checkbox-wrapper">
                <span className="ant-checkbox">
                  <span className="ant-checkbox-inner"></span>
                  <input type="checkbox" className="ant-checkbox-input" />
                </span>
              </label>
            </th>
            {
              <React.Fragment>
                {
                  coms.filter(Boolean).map(({ config }, i) => {
                    return (
                      <th key={`header_${config.title}`} className='data-table-title'>
                        <div className='wea-edc-com-title f-ellipsis' title={config.title}>
                          <label>
                            <span className={config.required === '1' ? 'wea-edc-com-required' : undefined}>
                              {config.title}
                            </span>
                          </label>
                          {!config.desc ? null : <label className='wea-edc-com-desc' dangerouslySetInnerHTML={{ __html: config.desc }} />}
                        </div>
                      </th>
                    );
                  })
                }
              </React.Fragment>
            }
          </tr>
        </thead>
        <tbody>
          <tr>
            <td className='mobile-edc-app-tablecheckbox'>
              <label className="ant-checkbox-wrapper">
                <span className="ant-checkbox">
                  <span className="ant-checkbox-inner"></span>
                  <input type="checkbox" className="ant-checkbox-input" />
                </span>
              </label>
            </td>
            {
              coms.filter(Boolean).map((com, colIndex) => (
                  <td key={`mobileDataTable${com.uuid}${colIndex}`} className='mobile-data-table-item'>
                  {renderItem(com)}
                  </td>
                ))
            }
          </tr>
        </tbody>
      </table>
    </div>
  );
}

const MapView = ({ data, value }) => {
  const defaultLocation = () =>  getLabel('502506', '上海市泛微网络科技有限公司');
  const mapEvents = {
    created: (mapInstance) => {
      const map = mapInstance;

      window.AMap.plugin(['AMap.PlaceSearch', 'AMap.Geocoder'], () => {
        const placeSearch = new window.AMap.PlaceSearch();
        const marker = new window.AMap.Marker();

        getLocation(map, placeSearch, marker, data.location || defaultLocation());
      });
    }
  }

  const getLocation = (map, placeSearch, marker,address) => {//定位到设置的位置
    placeSearch.search(address, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        map.remove(marker);
        map.add(marker);
        marker.setPosition(result.poiList.pois[0].location);
        map.setFitView(marker);
      }
    });
  }

  return (
    <div className='wea-edc-map-conatiner'>
      <Map
        zoom={5}
        jogEnable={false}
        animateEnable={false}
        events={mapEvents} 
        center={{ longitude: 120, latitude: 30 }}
      />
    </div>
  );
}

export class TableLayoutView extends React.Component {

  state = {
    width: 0
  }

  container = React.createRef();

  componentDidMount() {
    const borderWidth = 1;
    const dom = this.container.current;

    this.setState({
      width: dom.offsetWidth - 2 * borderWidth
    });
  }

  renderCell = (cell, index) => {
    if (!cell) return null;

    const { width } = this.state;
    const { data, renderItem } = this.props;
    const totalspan = data.grid[0].length;
    const { rowspan, colspan } = cell;
    const widthPct = getWidthPct(colspan, totalspan);
    const cellWidth = getWidthPX(width, widthPct);
    const com = cell.comId && data.coms.find(com => com.uuid === cell.comId);

    return (
      <td key={`cell${index}${cell.comId}`} width={cellWidth} colSpan={colspan} rowSpan={rowspan}>
        {renderItem(com)}
      </td>
    );
  }

  render () {
    const { data } = this.props;

    return (
      <div className='wea-edc-table-wrapper' ref={this.container}>
        <table>
          <tbody>
            {data.grid.map((cells, index) => (
              <tr key={`edcTable${index}`}>{cells.map(this.renderCell)}</tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
}

export class BoardElementView extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      loaded: false,
      info: '',
      them: '',
      loading: true
    };
  }

  componentDidMount() {
    this.loadEdcBoard();

    const date = new Date();
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const { defaultValue } = this.props.data;

    if (defaultValue) {
      this.setState({ loading: true });

      widget.getInfo(defaultValue).then(data => {
        board.getBoardInfo(data.board).then(boardInfo => {
          this.setState({
            loading: false,
            info: data,
            them: boardInfo.theme || 'default'
          });
        });
      });

    }
  }

  loadEdcBoard() {
    const MOD_NAME = 'weaEdcBoard4Mobile';

    if (loadjs.isDefined(MOD_NAME)) {
      this.setState({loaded: true});
    } else {
      const LIB_URL = '/spa/edc/static4engine/board4mobile';

      loadjs(
        [
          `${LIB_URL}/index.js`,
          `${LIB_URL}/index.css`
        ],
        MOD_NAME, {
          success: () => {
            this.setState({ loaded: true });
          }
        }
      )
    }
  }

  render() {
    const { defaultValue,  chartHeight, chartType } = this.props.data;
    const { modeType } = this.props;
    const { info, them = {} } = this.state;
    const search = window.location.search.replace('?', '');
    let { data: dt } = querystring.parse(search);
    let finalBaseInfo = [];
    let finalHeight = Number(chartHeight);
    const coms = window.weaEdcBoard4Mobile;

    if (chartType === 'DIGITALPANEL' || chartType === 'DATAPANEL') {
      finalHeight = 'auto';
    }

    if (!coms || (!defaultValue && modeType === modeTypes.VIEW)) return null;
    if (!defaultValue && modeType === modeTypes.DESIGN) return (<div className='board-element-view'><label className='text'>{getLabel('519598', '选择图表元素')}</label></div>);
   
    const { title } = getUrlParams();

    if (title === 'none' && info) {
      info.name = '';
    }

    if (info) {
      info.params = { ...getUrlParams(), ...finalBaseInfo };
    }

    const clsNameStr = classNames(`wea-edc-board-single-chart rp-layout-${them}`, {
      'notitle': title === 'none',
    });

    return (
      <div className={`board-element-view ${clsNameStr}`} style={{ height: finalHeight }}>
        <If condition={this.state.loading}>
          <Then>
            <div style={{height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
              <Icon type='loading' />
            </div>
          </Then>
          <Else>
            <coms.ChartView theme={them} height='100%' info={info} baseInfo={finalBaseInfo} />
          </Else>
        </If>
      </div>
    );
  }
}


export default {
  [TEXT]: Text,
  [DATE]: DateView,
  [TIME]: TimeView,
  [TEXTAREA]: TextareaView,
  [SELECT]: SelectView,
  [COMBOBOX]: ComBoboxView,
  [NUMBER]: NumberView,
  [DESCRIPTION]: DescriptionView,
  [RATING]: RatingView,
  [SIGNATURE]: SignatureView,
  [PICTURE]: PictureView,
  [ATTACHMENT]: AttachmentView,
  [NAME]: NameView,
  [MOBILE]: MobileView,
  [EMAIL]: EmailView,
  [TELEPHONE]: TelePhoneView,
  [ADDRESS]: AddressView,
  [COLUMNPANEL2]: ColumnPanel2View,
  [COLUMNPANEL3]: ColumnPanel2View,
  [DATATABLE]: DataTableView,
  [MAP]: MapView,
  [TABLELAYOUT]: TableLayoutView,
  [BOARD_ELEMENT]: BoardElementView
}